var crypto = require("crypto");


var express = require("express");
var passport = require("passport");
var Strategy = require('passport-local').Strategy;
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });


var user = require("../model/user");


passport.use(
    "local",
    new Strategy(
        function(username, password, cb) {

            var md5 = crypto.createHash("md5");
            md5.update(password);
            var sign = md5.digest("hex");
            user.findOne({ name: username, password: sign }, function(err, doc) {
                if (doc) {
                    return cb(null, doc);
                } else {
                    return cb(null, false);
                }
            });

        }
    )
);

passport.serializeUser(function(user, cb) {
    cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {

    user.findById(id, function(err, user) {
        cb(err, user);
    });
});
var router = express.Router();

router.get("/login", function(req, res) {
    res.render("auth", { layout: "auth", login: true });
});

router.get("/register", function(req, res) {
    res.render("auth", { layout: "auth", login: false });
});


router.post("/login", urlencodedParser, function(req, res, next) {

    passport.authenticate("local", function(err, user, info) {
        if (err) {
            next(err);
        } else if (!user) {

            res.send({ code: 0, status: -1, message: "登录失败" });
        } else {
            console.log(user);
            req.logIn(user, function(err) {
                var returnTo = "/editor";
                if (err) {
                    next(err);
                } else {
                    if (req.session.returnTo) {
                        returnTo = req.session.returnTo;
                    }

                    res.send({ code: 0, status: 0, message: "登录成功", goto: returnTo });
                }
            });
        }
    })(req, res, next);
});


router.get("/logout", function(req, res, next) {

    req.logOut();
    res.redirect("/login");
});

router.post("/register", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    user.create({
            name: username,
            password: sign
        },
        function(err, doc) {

            res.redirect("/login");
        }
    );
});

module.exports = router;